package cur.nature.component.nacos.config;

import cur.nature.component.nacos.handler.CustomExchangeFilterFunction;
import cur.nature.component.nacos.property.RestConfig;
import io.netty.channel.ChannelOption;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.loadbalancer.reactive.ReactorLoadBalancerExchangeFilterFunction;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.time.Duration;

@Configuration
@ConditionalOnProperty( value = {"cur.component.nacos.enable"})
public class WebClientConfig {

    @Bean
    public WebClient webClient(ReactorLoadBalancerExchangeFilterFunction function, RestConfig restConfig) {
        HttpClient httpClient = HttpClient.create()
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, restConfig.getReadTimeout()*1000) // 连接超时
                .responseTimeout(Duration.ofMillis(restConfig.getConnectTimeout()*1000)); // 读取超时
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .filter(new CustomExchangeFilterFunction())
                .filter(function).build();
    }
}
